package com.study.util;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.study.model.User;

import redis.clients.jedis.Jedis;

public class RedisSerializable {
	
	private static RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);

	public static void main(String[] args) {
		
		User user = new User(1,"张三",18);
		int timeout = 5*60;
		//将user对象存入redis
		String result = putUser(user,timeout);
		System.out.println("返回结果：" + result);
		
		User user1 = getUser(1);
		System.out.println(user1.toString());
	}
	
	public static String putUser(User user,int timeout) {
		String result = "";
		try {
			Jedis jedis = RedisUtil.getJedis();
			try {
				String key = "user:" + user.getId();
				byte[] bytes = ProtostuffIOUtil.toByteArray(user, schema, 
						LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
				result = jedis.setex(key.getBytes(), timeout, bytes);
				return result;
			}finally {
				jedis.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static User getUser(int id) {
		try {
			Jedis jedis = RedisUtil.getJedis();
			try {
				String key = "user:"+id;
				byte[] bytes = jedis.get(key.getBytes());
				if(bytes != null && bytes.length>0) {
					User user = schema.newMessage();
					ProtostuffIOUtil.mergeFrom(bytes, user, schema);
					
					return user;
				}
			}finally {
				jedis.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
